package net.ru.topdog.lunchy.menu;

import java.util.ArrayList;
import java.util.List;

import java.math.BigDecimal;

import net.ru.topdog.lunchy.Dish;
import net.ru.topdog.lunchy.dao.DAOFactory;


public class MenuModel implements MenuModelInterface {
	private int mode;
	private String configFile;
	private List<MenuViewObserverInterface> observers = new ArrayList<MenuViewObserverInterface>();
	private List<Dish> dishes = new ArrayList<Dish>();
	private List<String> types = new ArrayList<String>();

	@Override
	public void registerMenuViewObserver(MenuViewObserverInterface o) {
		observers.add(o);

	}

	@Override
	public void removeMenuViewObserver(MenuViewObserverInterface o) {
		int i = observers.indexOf(o);
		if (i >= 0) {
			observers.remove(i);
		}

	}
	//!! To be divided this method!!!!!!!! (dish and type and maybe other if to be)(param)
	public void notifyMenuViewObservers() {
		for (MenuViewObserverInterface observer : observers) {
			observer.updateMenuView();
		}
	}

	public List<Dish> getDishs() {
		return dishes;
	}

	public void setDishs(List<Dish> dishs) {
		this.dishes = dishs;
	}

	@Override
	public void addDish(String type, String name, String desc, String cost) {
		int idDish = dishes.size() + 1;
		Dish dish = new Dish(idDish, type, name, desc, new BigDecimal(cost));
		dishes.add(dish);
		notifyMenuViewObservers();
	}
	
	
	@Override
	public void editDish(int id, String type, String name, String desc,
			String cost) {
		id--;
		dishes.get(id).setType(type);
		dishes.get(id).setName(name);
		dishes.get(id).setDesc(desc);
		dishes.get(id).setCost(new BigDecimal(cost));

		notifyMenuViewObservers();

	}

	@Override
	public void deleteDish(int id) {
		if (id < dishes.size() + 1) {
			dishes.remove(id - 1);
			for (Dish d : dishes) {
				if (id < d.getId()) {
					d.setId(d.getId() - 1);
				}
			}
			//!! to be divided this method
			notifyMenuViewObservers();
		}
	}

	@Override
	public void addType(String type) {
		types.add(type);
		//!! to be divided this method
		notifyMenuViewObservers();
	}



	@Override
	public void save() {
		DAOFactory f = DAOFactory.getDAOFactory(mode, configFile);
		f.getDishDAO().save(dishes);
		f.getTypeDAO().save(types);
		
	}

	@Override
	public void load() {
		DAOFactory f = DAOFactory.getDAOFactory(mode, configFile);
		dishes=f.getDishDAO().load();
		types=f.getTypeDAO().load();
		notifyMenuViewObservers();
		
	}

	public void setConfigFile(String configFile) {
		this.configFile = configFile;
	}

	@Override
	public void setMode(int mode) {
		this.mode=mode;
		
	}

	@Override
	public List<String> getTypes() {
		return types;
	}

	@Override
	public void deleteType(int selectType) {
		types.remove(selectType);
		notifyMenuViewObservers();
	}

}
